package com.example.order.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.example.order.IGoodsService;
import com.example.order.constant.ShopCode;
import com.example.order.entity.Result;
import com.example.order.entity.TradeGoods;
import com.example.order.entity.TradeGoodsNumberLog;
import com.example.order.exception.CastException;
import com.example.order.mapper.TradeGoodsMapper;
import com.example.order.mapper.TradeGoodsNumberLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: songyahui
 * @Date: 2020/11/10 18:15
 * @Version 1.0
 */
@Component
@Service(interfaceClass = IGoodsService.class)
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private TradeGoodsMapper goodsMapper;

    @Autowired
    private TradeGoodsNumberLogMapper goodsNumberLogMapper;

    public TradeGoods findOne(Long goodsId){
        if(goodsId==null){
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        return goodsMapper.selectByPrimaryKey(goodsId);
    }

    @Override
    public int insert(TradeGoods goods) {

        return goodsMapper.insert(goods);
    }

    @Override
    public Result reduceGoodsNum(TradeGoodsNumberLog goodsNumberLog) {
        if(goodsNumberLog==null ||
            goodsNumberLog.getGoodsNumber()==null ||
                    goodsNumberLog.getGoodsNumber()==null ||
                    goodsNumberLog.getOrderId()==null ||
                    goodsNumberLog.getGoodsNumber()==null ||
                    goodsNumberLog.getGoodsNumber()==null){
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        TradeGoods goods = goodsMapper.selectByPrimaryKey(goodsNumberLog.getGoodsId());
        if(goods.getGoodsNumber()<goodsNumberLog.getGoodsNumber()){
//          //库存不足
            CastException.cast(ShopCode.SHOP_GOODS_NUM_NOT_ENOUGH);
        }
//       减库存
        goods.setGoodsNumber(goods.getGoodsNumber()-goodsNumberLog.getGoodsNumber());
        goodsMapper.updateByPrimaryKey(goods);
//        记录库存操作日志
        goodsNumberLog.setGoodsNumber(-goodsNumberLog.getGoodsNumber());
        goodsNumberLog.setLogTime(new Date());
        goodsNumberLogMapper.insert(goodsNumberLog);
        return new Result(ShopCode.SHOP_SUCCESS.getSuccess(),ShopCode.SHOP_SUCCESS.getMessage());
    }
}
